<template>
    <u-upload
        :fileList="fileList1"
        @afterRead="afterRead"
        @delete="deletePic"
        name="1"
        multiple
        :maxCount="10"
    ></u-upload>
</template>

<script>
export default {
    data() {
        return {
            fileList1: [],
        };
    },
    methods: {
        // 删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1);
        },
        // 新增图片
        async afterRead(event) {
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            console.log({ lists });
            let fileListLen = this[`fileList${event.name}`].length;
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中',
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                let item = this[`fileList${event.name}`][fileListLen];
                this[`fileList${event.name}`].splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
                uni.compressImage({
                    src: url, // 图片路径
                    quality: 1, // 压缩质量，范围0-100
                    success: function (compressImageRes) {
                        // /file/upload
                        console.log('压缩后的图片路径:', compressImageRes);
                        const filePath = compressImageRes.tempFilePath;

                        uni.uploadFile({
                            url: 'http://localhost:9999/file/upload/images',
                            filePath,
                            name: 'file',
                            formData: {
                                user: 'test',
                            },
                            success: (res) => {
                                console.log(222, res);
                                resolve(res.data);
                            },
                        });
                    },
                    fail: function (err) {
                        console.error('图片压缩失败:', err);
                    },
                });
            });
        },
    },
};
</script>
